import { flipCardData, FlipService } from "@/popup/services/flip";
import { Empty, Card, Button, message, Radio } from "antd";
import React, { useEffect, useState, useMemo } from "react";
import ReactECharts from "echarts-for-react";
import { useUserStore } from "@/popup/stores/user";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import dayjs from "dayjs";

const Analysis: React.FC = () => {
  const [groupedDataById, setGroupedDataById] = useState<Record<
    string,
    flipCardData
  > | null>(null);
  const [currentPage, setCurrentPage] = useState(0);
  const [timeMode, setTimeMode] = useState<'daily' | 'monthly'>('monthly');
  const { token, userInfo } = useUserStore();


  useEffect(() => {
    chrome.storage.local.get("groupedDataById", (result) => {
      setGroupedDataById(result.groupedDataById || null);
    });
  }, []);

  const handleClick = async () => {
    try {
      message.info("拉取信息中... 耗时可能较长");
      await FlipService.getAllFlips(token, userInfo?.userInfo?.userId);
      message.success("拉取信息成功");

      // 重新获取数据并刷新页面
      chrome.storage.local.get("groupedDataById", (result) => {
        setGroupedDataById(result.groupedDataById || null);
      });
    } catch (error) {
      message.error("拉取信息失败");
    }
  };

  // 处理图表数据
  const chartData = useMemo(() => {
    if (!groupedDataById) return null;

    const data = Object.values(groupedDataById).map((user) => ({
      name: user.xoxNickname || `用户${user.xoxId}`,
      value: user.cards.length,
      userId: user.xoxId,
    }));

    // 按翻牌数量排序
    return data.sort((a, b) => b.value - a.value);
  }, [groupedDataById]);

  // 处理时间趋势数据
  const timeTrendData = useMemo(() => {
    if (!groupedDataById) return null;

    const timeStats: Record<string, number> = {};
    
    Object.values(groupedDataById).forEach((user) => {
      user.cards.forEach((card) => {
        const timestamp = Number(card.qtime);
        let timeKey: string;
        
        if (timeMode === 'daily') {
          // 按天统计
          timeKey = dayjs(timestamp).format('YYYY-MM-DD');
        } else {
          // 按月统计
          timeKey = dayjs(timestamp).format('YYYY-MM');
        }
        
        timeStats[timeKey] = (timeStats[timeKey] || 0) + 1;
      });
    });

    // 转换为数组并排序
    const sortedData = Object.entries(timeStats)
      .map(([date, count]) => ({ date, count }))
      .sort((a, b) => a.date.localeCompare(b.date));

    return {
      dates: sortedData.map(item => item.date),
      counts: sortedData.map(item => item.count)
    };
  }, [groupedDataById, timeMode]);

  // 柱状图配置
  const barOption = useMemo(() => {
    if (!chartData) return {};

    return {
      title: {
        text: "用户翻牌数量统计",
        left: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: function (params: any) {
          const data = params[0];
          return `${data.name}<br/>翻牌数量: ${data.value}`;
        },
      },
      grid: {
        left: "7%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: chartData.map((item) => item.name),
        axisLabel: {
          rotate: 45,
          fontSize: 12,
        },
      },
      yAxis: {
        type: "value",
        name: "翻牌数量",
        nameLocation: "middle",
        nameGap: 30,
      },
      series: [
        {
          name: "翻牌数量",
          type: "bar",
          data: chartData.map((item) => ({
            value: item.value,
            itemStyle: {
              color: "#1890ff",
            },
          })),
          barWidth: "60%",
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
          },
        },
      ],
    };
  }, [chartData]);

  // 饼图配置 - 显示翻牌类型分布
  const pieOption = useMemo(() => {
    if (!groupedDataById) return {};

    const typeStats: Record<number, number> = {};
    Object.values(groupedDataById).forEach((user) => {
      user.cards.forEach((card) => {
        typeStats[card.type] = (typeStats[card.type] || 0) + 1;
      });
    });

    const pieData = Object.entries(typeStats).map(([type, count]) => ({
      name: `${type === '0' ? '公开' : type === '1' ? "匿名": "私密"}`,
      value: count,
    }));

    return {
      title: {
        text: "翻牌类型分布",
        left: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)",
      },
      xAxis: {
        show: false,
      },
      yAxis: {
        show: false,
      },
      series: [
        {
          name: "翻牌类型",
          type: "pie",
          radius: "50%",
          center: ["50%", "50%"],
          data: pieData,
          label: {
            show: true,
            formatter: "{b}: {c} ({d}%)",
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
  }, [groupedDataById]);

  // 折线图配置 - 显示时间趋势
  const lineOption = useMemo(() => {
    if (!timeTrendData) return {};

    return {
      title: {
        text: `翻牌数量${timeMode === 'daily' ? '每日' : '每月'}趋势`,
        left: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
        },
        formatter: function (params: any) {
          const data = params[0];
          return `${data.name}<br/>翻牌数量: ${data.value}`;
        },
      },
      grid: {
        left: "7%",
        right: "4%",
        bottom: "10%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: timeTrendData.dates,
        axisLabel: {
          rotate: 45,
          fontSize: 10,
        },
      },
      yAxis: {
        type: "value",
        name: "翻牌数量",
        nameLocation: "middle",
        nameGap: 30,
      },
      series: [
        {
          name: "翻牌数量",
          type: "line",
          data: timeTrendData.counts,
          smooth: true,
          lineStyle: {
            color: "#52c41a",
            width: 3,
          },
          itemStyle: {
            color: "#52c41a",
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(82, 196, 26, 0.3)" },
                { offset: 1, color: "rgba(82, 196, 26, 0.1)" },
              ],
            },
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
          },
        },
      ],
    };
  }, [timeTrendData, timeMode]);

  // 图表配置数组
  const charts = useMemo(() => {
    if (!groupedDataById) return [];
    
    return [
      {
        title: `翻牌数量${timeMode === 'daily' ? '每日' : '每月'}趋势`,
        option: lineOption,
        showTimeModeControl: true,
      },
      {
        title: "用户翻牌统计",
        option: barOption,
      },
      {
        title: "翻牌类型分布",
        option: pieOption,
      },
    ];
  }, [groupedDataById, barOption, pieOption, lineOption, timeMode]);

  const handlePrevPage = () => {
    setCurrentPage((prev) => Math.max(0, prev - 1));
  };

  const handleNextPage = () => {
    setCurrentPage((prev) => Math.min(charts.length - 1, prev + 1));
  };

  if (!groupedDataById || charts.length === 0) {
    return (
      <div>
        <div
          style={{
            cursor: "pointer",
            color: "#1890ff",
          }}
          onClick={handleClick}
        >
          拉取信息
        </div>
        <Empty description="暂无数据" />
      </div>
    );
  }

  return (
    <div
      style={{
        padding: "4px",
        height: "calc(100vh - 100px)",
        overflow: "auto",
        boxSizing: "border-box",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <h3 style={{ marginBottom: "4px", textAlign: "center" }}>数据分析</h3>

      <div style={{ flex: 1, position: "relative" }}>
        <Card 
          title={charts[currentPage].title} 
          bordered={false} 
          style={{ height: "100%" }}
          extra={
            charts[currentPage].showTimeModeControl ? (
              <Radio.Group 
                value={timeMode} 
                onChange={(e) => setTimeMode(e.target.value)}
                size="small"
              >
                <Radio.Button value="daily">每日</Radio.Button>
                <Radio.Button value="monthly">每月</Radio.Button>
              </Radio.Group>
            ) : null
          }
        >
          <ReactECharts
            key={`chart-${currentPage}-${timeMode}`}
            option={charts[currentPage].option}
            // style={{ height: "calc(100% - 60px)" }}
            opts={{ renderer: "canvas" }}
            notMerge={true}
          />
        </Card>

        {/* 分页按钮 */}
        <div
          style={{
            position: "absolute",
            bottom: "10px",
            left: "50%",
            transform: "translateX(-50%)",
            display: "flex",
            alignItems: "center",
            gap: "8px",
            background: "rgba(255, 255, 255, 0.9)",
            padding: "4px 12px",
            borderRadius: "16px",
            boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
          }}
        >
          <Button
            type="text"
            icon={<LeftOutlined />}
            onClick={handlePrevPage}
            disabled={currentPage === 0}
            size="small"
          />
          <span style={{ fontSize: "12px", color: "#666" }}>
            {currentPage + 1} / {charts.length}
          </span>
          <Button
            type="text"
            icon={<RightOutlined />}
            onClick={handleNextPage}
            disabled={currentPage === charts.length - 1}
            size="small"
          />
        </div>
      </div>
    </div>
  );
};

export default Analysis;
